package com.demo.function.spring.feign.interceptor;

import com.demo.function.spring.loadbalancer.GrayRequestContextHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * feign拦截器
 * 获取请求头gray属性，设置request对象线程共享
 * @author K
 */
@Slf4j
@Component
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        log.info("feign拦截器，当前ServletRequestAttributes对象是否为空：{}", attributes == null);
        if (attributes != null) {
            // 设置子线程共享
            RequestContextHolder.setRequestAttributes(attributes, true);
            // 设置请求头
            requestTemplate.header(GrayRequestContextHolder.GRAY, GrayRequestContextHolder.getGray().toString());
        }
    }
}
